import 'package:dio/dio.dart';
import 'package:get/get.dart';

import 'oi_response.dart';

/// 自定义异常
class AppException implements Exception {
  final String _message;
  final int _code;
  final CommonResult? data;

  AppException(
    this._code,
    this._message, {
    this.data,
  });

  @override
  String toString() {
    return _message;
  }

  int get code => _code;
  String get message => _message;

  factory AppException.create(DioException error) {
    switch (error.type) {
      case DioExceptionType.cancel:
        {
          return BadRequestException(-1, "request_cancel".tr);
        }
      case DioExceptionType.connectionTimeout:
        {
          return BadRequestException(-1, "request_connectionTimeout".tr);
        }
      case DioExceptionType.sendTimeout:
        {
          return BadRequestException(-1, "request_sendTimeout".tr);
        }
      case DioExceptionType.receiveTimeout:
        {
          return BadRequestException(-1, "request_receiveTimeout".tr);
        }
      case DioExceptionType.connectionError:
        {
          return BadRequestException(-1, "request_connectionError".tr);
        }
      case DioExceptionType.badResponse:
        {
          try {
            int? errCode = error.response!.statusCode;
            // String errMsg = error.response.statusMessage;
            // return ErrorEntity(code: errCode, message: errMsg);
            return BadRequestException(errCode!, errCode.toString().tr);
          } on Exception catch (_) {
            return AppException(-1, "unknown_error".tr);
          }
        }
      default:
        {
          try {
            // 业务异常
            final commonResult = error.error as CommonResult;
            var errorMsg = commonResult.code!.toString().tr;
            return AppException(commonResult.code!, errorMsg,
                data: commonResult);
          } catch (error) {
            return AppException(-1, error.toString(), data: null);
          }
        }
    }
  }
}

/// 请求错误
class BadRequestException extends AppException {
  BadRequestException(super.code, super.message);
}

/// 未认证异常
class UnauthorisedException extends AppException {
  UnauthorisedException(super.code, super.message);
}
